import { Component, OnInit } from '@angular/core';
import {UtilService} from "../../my-service/util.service";
import {TrainingService} from "../../my-service/training.service";
import {Training} from "../Training";
import {Router,ActivatedRoute} from "@angular/router";
import {NzModalService, NzMessageService} from 'ng-zorro-antd';

@Component({
  selector: 'app-training-minute',
  templateUrl: './training-minute.component.html',
  styleUrls: ['./training-minute.component.css'],
})
export class TrainingMinuteComponent implements OnInit {
  projectName='wt';
  userGuid:string;
  classGuid:string;
  className:string;
  trainingList=[];//所有的训练
  trainingByMonthGroups =[];//存放按照月份分组好的训练
  monthList =[];//存放月份日期
  lastYear =null;//存放当前显示最后一月的年份
  lastMonth=null;//存放当前显示月份的最后一月的年份
  isEdit:boolean;//是否处于编译状态下
  addTest:boolean;//添加测试
  isClassAdd:boolean;//是否班级添加测试
  modifyTraining:null;//需要修改的测试
  modifyIndex=[];//当前修改测试的索引
  constructor(
    private utilServe: UtilService,
    private trainingService: TrainingService,
    private  route:Router,
    private  routerInfo:ActivatedRoute,
    private message: NzMessageService,
  ) { }
  // 根据训练列表查询邀请码
  getCodeByTrainingList(trainingList){
    let nowTime = this.utilServe.getCurrentTime();
    trainingList.forEach(training=>{
      this.trainingService.getCodeBytrainingId(training.id).then(res=>{
        if(res.status==1){
          training.inviteCode=res.code;
          training.inviteCodeGuid=res.guid;
          if(res.EndTime>=nowTime){
            training.codeEnd=false;
          }
        }
      })
    })
  }
  //获取班级测试列表
  getTrainingList(userGuid,classGuid){
    this.trainingService.getTrainingByClass(userGuid,classGuid).then(res=>{
      if(res.status==1){
        res.data.forEach(val => {
          this.trainingList.push(new Training(val.PK_TrainingGuid, val.TrainingName, val.Description, this.userGuid, null, true,val.CreateTime, null, null,val.FK_ClassGuid))
        });
        this.getCodeByTrainingList(this.trainingList);
        this.getTrainingStus(this.trainingList);
        this.getTrainingByMonth();
      }
    })
  }
  /*初始默认获取2个月的*/
  getTrainingByMonth() {
    //按照月份查看，默认获取2个月的;
    this.trainingByMonthGroups = [];//清空之前按月分组的训练
    this.monthList = [];
    let date = new Date();
    let currentYear = date.getFullYear();
    let currentMonth = date.getMonth() + 1;
    let lastYear, lastMonth;
    if (currentMonth == 1) {
      lastYear = currentYear - 1;
      lastMonth = 12;
    } else {
      lastYear = currentYear;
      lastMonth = currentMonth - 1;
    }
    //获取当前显示的月份
    this.monthList.push(currentMonth);
    this.monthList.push(lastMonth);
    //获取当前显示第一个月的月份
    this.lastYear = lastYear;
    this.lastMonth = lastMonth;
    //获取当前2个月的训练
    let currentMonthTrainingList = this.trainingByMonthGroup(this.trainingList, currentYear, currentMonth);
    let lastMonthTrainingList = this.trainingByMonthGroup(this.trainingList, lastYear, lastMonth);
    this.trainingByMonthGroups.push(currentMonthTrainingList);
    this.trainingByMonthGroups.push(lastMonthTrainingList);

  }
  /*获取参加训练的人数*/
  getTrainingStus(trainingList){
    trainingList.forEach(training=>{
      this.trainingService.getAnswerCardByTrainingId(training.id).then(res=>{
        if(res.status==1){
          training.studentNum=res.data.length;
        }
      })
    })
  }
  ngOnInit() {
    this.classGuid = this.routerInfo.snapshot.params.classID;
    this.className = this.routerInfo.snapshot.params.className;
    this.utilServe.getUserInfo().then(res => {
      this.userGuid = res.userGuid;//获取用户的guid
      this.getTrainingList(this.userGuid,this.classGuid);
    })
  }
  //跳回首页
  goToStart(){
    this.route.navigate(['home/start']);
  }
  /*将训练根据月份来进行分组*/
  trainingByMonthGroup(trainings, year, month) {
    let monthList = [];
    let firstTime = this.utilServe.getDateTimeOfFirstDay(year, month);//获取每月第一天的时间戳
    let lastTime = this.utilServe.getDateTimeOfLastDay(year, month);//获取每月最后一天的时间戳
    trainings.forEach(training => {
      if (training.createTime >= firstTime && training.createTime <= lastTime) {
        monthList.push(training);
      }
    });
    return monthList;
  }
  /*添加测试*/
  addTraining(){
    this.addTest = true;
    this.isClassAdd = true;
  }
  /*关闭测试*/
  onCloseAdd(training) {
    this.addTest = false;
    /*是否有新增测试*/
    this.isClassAdd =false;
    if(training.id&&!this.modifyTraining){
      //新添加的，推入当月测试
      this.trainingByMonthGroups[0].push(training);
    }
    if(training.id&&this.modifyTraining){
      //替换原来的测试
      this.trainingByMonthGroups[this.modifyIndex[0]][this.modifyIndex[1]]=training;
      this.modifyIndex=[];//修改完成清空索引
    }
    this.modifyTraining=null
  }
  /*修改测试*/
  modifyOfTraining(training,i,j){
    this.addTest = true;
    this.isClassAdd = true;
    this.modifyTraining = training;
    this.modifyIndex = [i,j];
  }
  /*删除测试*/
  deleteOfTraining(training,i,j){
    this.utilServe.comfirm(`您确认要删除${training.name}嘛？`,()=>{
      this.trainingService.deleteInviteCode(training.inviteCodeGuid).then(res=>{});
      this.trainingService.deleteTraining(training.id).then(res=>{
        if(res.status==1){
          this.message.success(`删除${training.name}成功`);
          this.trainingByMonthGroups[i].splice(j,1);
        }else {
          this.message.error(`删除${training.name}失败,请稍后再试`);
        }
      })
    })
  }
// 点击获取上个月的值
  getLastMonth() {
    let month, year;
    if (this.lastMonth == 1) {
      month = 12;
      year = this.lastYear - 1;
    } else {
      month = this.lastMonth - 1;
    }
    let monthTrainings = this.trainingByMonthGroup(this.trainingList, year, month);//获取当前月份分组的数据
    this.trainingByMonthGroups.push(monthTrainings);
    this.monthList.push(month);
    //改变第一个月的值
    this.lastYear = year;
    this.lastMonth = month;
  }
  //去到某个测试详情页
  jumpRoster(training){
    if(!this.isEdit){
      this.route.navigate(['../roster',{ID:training.id,className:training.className,classID:training.classGuid}],{relativeTo:this.routerInfo});
    }
  }
  /*创建邀请码*/
  createCode(event,training){
    event.stopPropagation();
    let endTime = new Date();
    endTime.setMonth(endTime.getMonth() + 6); //设置结束时间为6个月以后
    let LibQuery=`;className=${this.className};classID=${this.classGuid}`;
    let data={
      projectName:this.projectName,
      guid:training.PK_TrainingGuid,
      FK_ClassGuid:this.classGuid,
      endTime,
      LibQuery
    };
    this.trainingService.createCode(data).then(res=>{
      if(res.status==1){
        training.inviteCode = res.code;
        training.codeEnd=false;
      }
    });
  }

}
